<?php
$file = "scores.txt";

$name = $_POST["name"];
$score = $_POST["score"];

$sr = fopen($file, "r");
$a = array();
while (($data = fgetcsv($sr, 200, ",")) !== FALSE) {
	$a[] = $data;
}
usort($a, comp);

$rank = 0;
if ($name && $score && md5($_POST["pass"]) == "6c22bb826771f6cb66691c24691ab425")
{

$l = count($a);
foreach ($a as $v)
{
	if ($v[1] < $score)
	{
		$p1 = array_slice($a, 0, $rank);
		$p1[] = array($name, $score);
		$p2 = array_slice($a, $rank);
		$a = array_merge($p1, $p2);
		$rank++;
		break;
	}
	$rank++;
	if ($rank == $l)
	{
		$a[] = array($name, $score);
		$rank++;
	}
}

}

$num = 10;
echo "<scores rank='$rank/".count($a)."'>\n";
foreach ($a as $v)
{
	if ($num-- > 0)
	{
		echo "<item name='$v[0]' score='$v[1]'/>\n";
	}
}
echo "</scores>";
fclose($sr);

function comp($x, $y)
{
	return $x[1] < $y[1];
}

if ($name && $score)
{
$sa = fopen($file, "a");
$entry = "\n".$name.",".$score;
fwrite($sa, $entry);
fclose($sa);
}
?>